import { Reducer, Effect, Subscription, history as umiHistory } from "umi"
import { message } from "antd"
import {
  IConsultDetails,
  IConsultReport,
  consultDetails as consultDetailsService,
  consultReport as consultReportService
} from "@/services/consultationDetail"


export interface IDetailState {
  details: IConsultDetails | null,// 会诊详情
  consultReport: IConsultReport | null// 会诊报告和病患信息
  consultId: number | null;// 会诊id
}

interface IDetailStateModelType {
  namespace: "conDetail";
  state: IDetailState;
  reducers: {
    setState: Reducer
  };
  effects: {
    getConsultDetails: Effect;// 获取会诊详情
    getConsultReport: Effect;// 获取//会诊报告和病患信息
  };
  subscriptions: {
    setup: Subscription;
  };
}

const ConsultationDetailModel: IDetailStateModelType = {
  namespace: "conDetail",
  state: {
    details: null,
    consultReport: null,
    consultId: null,
  },
  reducers: {
    setState(state: any, action: any) {
      return {
        ...state,
        ...action.payload,
      }
    }
  },
  effects: {
    *getConsultDetails({ payload }, { put, call }) {
      const { consultId } = payload
      try {
        let details = yield consultDetailsService(consultId)
        // call传参就是放在第二位
        // const data = yield call(getRemoteGoodList)
        if (details.code === 200 && details.data) {
          yield put({
            type: "setState",
            payload: {
              details: details.data,
              consultId: consultId
            },
          })
        } else {
          message.error(details.message)
        }
      } catch (error) {
        console.log(error)
      }

    },
    *getConsultReport({ payload }, { put, call }) {
      const { consultId } = payload
      let consultReport = yield consultReportService(consultId)
      // call传参就是放在第二位
      // const data = yield call(getRemoteGoodList)
      if (consultReport.code === 200 && consultReport.data) {
        yield put({
          type: "setState",
          payload: {
            consultReport: consultReport.data
          },
        })
      }
      else {
        message.error(consultReport.message)
      }
    }
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        if (pathname === "/consultationManagement/consultationDetail") {
          let consultId = umiHistory.location.query ? umiHistory.location.query.consultId : 3
          dispatch({
            type: "getConsultDetails",
            payload: {
              consultId: consultId
            },
          })
          dispatch({
            type: "getConsultReport",
            payload: {
              consultId: consultId
            },
          })
        }
      })
    },
  },
}

export default ConsultationDetailModel